#include"SeqList.h"

void SeqListInit(SL* ps) // 初始化
{
	ps->data = NULL;
	ps->size = 0;
	ps->capacity = 0;
}
void SeqListCheckCapacity(SL* ps)
{
	if (ps->size == ps->capacity)       //  增容
	{
		int newCapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
		SLDataType* temp = (SLDataType*)realloc(ps->data, sizeof(SLDataType) * newCapacity);
		if (temp == NULL)
		{
			printf("realloc fail\n");
			exit(-1);
		}
		ps->data = temp;
		ps->capacity = newCapacity;
	}
	// 增容完毕
}
void SeqListPushBack(SL* ps, int n)      // 顺序表追加数据
{
	//SeqListCheckCapacity(ps);
	//ps->data[ps->size] = n;
	//ps->size++;

	SeqListInsert(ps, ps->size, n);
}

void SeqListPrint(SL* ps)  // 顺序表数据打印
{
	for (int i = 0; i < ps->size; i++)
	{
		printf("%d ", ps->data[i]);
	}
}

void SeqListDestory(SL* ps) 
{
	free(ps->data);
	ps->data = NULL;
}

void SeqListPopBack(SL* ps) // 尾删
{
	/*if (ps->size > 0)
		ps->size--;
	else
		printf("无数据可删\n");*/

	//assert(ps->size > 0);    // 断言：括号内条件为真就不断言 ， 条件为假终止程序
	//ps->size--;

	SeqListErase(ps, ps->size-1);
}

void SeqListPushFront(SL* ps, SLDataType n)    // 前推
{
	//SeqListCheckCapacity(ps);

	//memmove(ps->data + 1, ps->data, ps->size * sizeof(SLDataType));    // 向后移动一个存储单元
	//ps->data[0] = n;
	//ps->size++;
	SeqListInsert(ps, 0, n);
}
 

// ------------------------------ homeword ------------------------------------
void SeqListPopFront(SL * ps) // 头删
{
	//assert(ps->size > 0);
	//assert(ps);
	//memmove(ps->data, ps->data + 1, sizeof(SLDataType) * ps->size - 1); // 前 -》后
	//ps->size--;
	SeqListErase(ps, 0);
}
int SeqListFind(SL* ps, SLDataType n) // 查找
{
	assert(ps);

	for (int i = 0; i < ps->size; i++)
	{
		if (ps->data[i] == n)
			return i;
	}
	return -1; // 没有找到
}

void SeqListInsert(SL* ps, int pos, SLDataType ele) // 插入
{
	assert(ps);
	assert(pos >= 0 && pos <= ps->size);

	SeqListCheckCapacity(ps);
	memmove(ps->data + pos + 1, ps->data + pos, (ps->size - pos) * sizeof(SLDataType));
	ps->data[pos] = ele;
	ps->size++;
}

void SeqListErase(SL* ps, int pos) // 删除
{
	assert(ps);
	assert(ps->size > 0);
	assert(pos < ps->size);
	memmove(ps->data + pos, ps->data + pos + 1, sizeof(SLDataType) * (ps->size - pos - 1));
	ps->size--;
}
